package com.lzw.DailyAudit.service.generateInvoices_03;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hooya.fa.eu.biz.DailyAudit.entity.DailyAuditStatus;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyAuditStatusMapper;
import com.hooya.fa.eu.biz.DailyAudit.service.dateAggregation_02.CommonService;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class AddInvoiceNo {

	@Autowired
	private CommonService commonService;

    private final DailyAuditStatusMapper statusMapper;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    
    // 构造函数
    public AddInvoiceNo(DailyAuditStatusMapper statusMapper) {
        this.statusMapper = statusMapper;
        // 直接创建RestTemplate实例，避免需要配置Bean
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();
    }


    /**
     * 调用接口获取补充发票信息
     * @param currentDate 日期参数（格式：yyyy-MM-dd）
     */
    public void getInvoiceNo(String currentDate) {
        String name = "AddInvoiceNo-03";
        DailyAuditStatus dailyAuditStatus = statusMapper.selectStatus(name, currentDate);
        if(dailyAuditStatus != null && dailyAuditStatus.getFlag() == 1){
            log.info("{} - 该方法已执行，进行跳过！",name);
            return;
        }

        // 构建请求URL
        String url = "http://192.168.0.116:8092/api/FADaily/SupplementInvoiceInfo?date=" + currentDate;
        log.info("调用接口获取补充发票信息: {}", url);

        try {
            // 先获取原始JSON字符串，避免类型转换错误
            String responseJson = restTemplate.getForObject(url, String.class);
            log.info("接口返回数据: {}", responseJson);
            
            // 解析JSON响应
            JsonNode rootNode = objectMapper.readTree(responseJson);
            int code = rootNode.path("code").asInt();
            String message = rootNode.path("message").asText();
            JsonNode dataNode = rootNode.path("data");
            
            // 处理响应结果
            if (code == 200) {
                log.info("获取补充发票信息成功，数据内容: {}", dataNode);

                // 从dataNode中获取maxDiff和minDiff对象
                JsonNode maxDiffNode = dataNode.path("maxDiff");
                JsonNode minDiffNode = dataNode.path("minDiff");

                // 获取maxDiff中的数据
                if (!maxDiffNode.isMissingNode()) {
                    String maxInvoiceNo = maxDiffNode.path("invoiceNo").asText();
                    double maxDiff = maxDiffNode.path("diff").asDouble();
                    if(maxDiff > 1){
                        log.error("发票价格差值过大，插值数据为：{}，插值发票为：{}", maxDiff, maxInvoiceNo);
                        throw new RuntimeException("最大差异发票差异值大于2");
                    }
                    log.info("最大差异发票: {}, 差异值: {}", maxInvoiceNo, maxDiff);
                }
                
                // 获取minDiff中的数据
                if (!minDiffNode.isMissingNode()) {
                    String minInvoiceNo = minDiffNode.path("invoiceNo").asText();
                    double minDiff = minDiffNode.path("diff").asDouble();
                    if(minDiff < -1){
                        log.error("发票价格差值过小，插值数据为：{}，插值发票为：{}", minDiff, minInvoiceNo);
                        throw new RuntimeException("最大差异发票差异值大于2");
                    }
                    log.info("最小差异发票: {}, 差异值: {}", minInvoiceNo, minDiff);
                }

            } else {
                log.warn("获取补充发票信息失败，错误码: {}, 错误信息: {}", code, message);
            }
        } catch (Exception e) {
            log.error("调用补充发票信息接口时发生错误: {}", e.getMessage(), e);
			XxlJobHelper.log("调用补充发票信息接口时发生错误: {}", e.getMessage());
        }

		// 修改执行状态
		commonService.UpdateOrInsertStatus(dailyAuditStatus, name, currentDate);

        log.info("调用发票接口成功");
		XxlJobHelper.log("调用发票接口成功");
    }

}
